package com.htc.callcare.datacontroller;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import com.android.internal.telephony.ITelephony;
import com.htc.callcare.R;
import com.htc.callcare.activities.VoiceMailActivity;
import com.htc.callcare.adapter.VoiceMailAdapter;
import com.htc.callcare.database.Database;
import com.htc.callcare.infrastructure.globalVar;
import com.htc.callcare.model.VoiceMailModel;
import com.htc.callcare.model.recordModel;

import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Handler;
import android.telephony.TelephonyManager;
import android.text.format.Time;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

public class VoiceMailFileController {
	Context context;
	static MediaRecorder recorder;
	static boolean timeOut;
	static boolean allowVoiceMail = false;

	

	
	public static boolean isAllowVoiceMail() {
		return allowVoiceMail;
	}

	public static void setAllowVoiceMail(boolean allowVoiceMail) {
		VoiceMailFileController.allowVoiceMail = allowVoiceMail;
	}

	public VoiceMailFileController(Context mContext) {
		super();
		this.context = mContext;

	}

	public void annswerPhoneHeadsethook() {
		Intent plugin1 = new Intent(Intent.ACTION_HEADSET_PLUG);
		plugin1.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
		plugin1.putExtra("state", 1);
		plugin1.putExtra("name", "Headset");
		context.sendOrderedBroadcast(plugin1,
				"android.permission.CALL_PRIVILEGED");

		// Simulate a press of the headset button to pick up the call
		Intent buttonDown = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonDown.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
				KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonDown,
				"android.permission.CALL_PRIVILEGED");

		// // froyo and beyond trigger on buttonUp instead of buttonDown
		Intent buttonUp = new Intent(Intent.ACTION_MEDIA_BUTTON);
		buttonUp.putExtra(Intent.EXTRA_KEY_EVENT, new KeyEvent(
				KeyEvent.ACTION_UP, KeyEvent.KEYCODE_HEADSETHOOK));
		context.sendOrderedBroadcast(buttonUp,
				"android.permission.CALL_PRIVILEGED");
		Intent plugin = new Intent(Intent.ACTION_HEADSET_PLUG);
		plugin.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
		plugin.putExtra("state", 0);
		plugin.putExtra("name", "Headset");
		context.sendOrderedBroadcast(plugin,
				"android.permission.CALL_PRIVILEGED");
	}

	public ITelephony getTelephonyService() {
		TelephonyManager telephonyManager = (TelephonyManager) context
				.getSystemService(context.TELEPHONY_SERVICE);
		Class clazz = null;
		Method method = null;
		ITelephony telephonyService = null;
		try {
			clazz = Class.forName(telephonyManager.getClass().getName());
			method = clazz.getDeclaredMethod("getITelephony");
			method.setAccessible(true);

			telephonyService = (ITelephony) method.invoke(telephonyManager);
		} catch (ClassNotFoundException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (SecurityException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (NoSuchMethodException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalArgumentException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (InvocationTargetException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		return telephonyService;
	}

	public void startrecord(String incomeCall/*, boolean Voicemail*/) {

		String name = "_";
		if (recorder == null/* && Voicemail*/) {
			recorder = new MediaRecorder();

			String path = globalVar.voiceMailDir;

			recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_DOWNLINK);
			recorder.setOutputFormat(MediaRecorder.OutputFormat.RAW_AMR);
			recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
			// Variable.recorder.setAudioEncodingBitRate(320);
			Date date = new Date();
			int minute = Calendar.getInstance().get(Calendar.MINUTE);
			DateFormat datef = new SimpleDateFormat(globalVar.FORMAT_DAY);
			name = "_" + Calendar.getInstance().get(Calendar.HOUR_OF_DAY) + "h"
					+ (((minute < 10) ? "0" : "") + minute) + "_"
					+ datef.format(date) + "_" + incomeCall + ".amr";

			name = "Voicemail" + name;

			path += name;
			recorder.setOutputFile(path);
			try {
				recorder.prepare();
				recorder.start();
				Log.e("thuutai", "Start record");
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
			AudioManager audioManager = (AudioManager) context
					.getSystemService("audio");
			audioManager
					.setStreamVolume(
							AudioManager.STREAM_VOICE_CALL,
							audioManager
									.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL),
							0);

			audioManager.setMicrophoneMute(true);
			// Log.e("debugg", "set mute");
		}

	}

	public void voiceMailEndRecord(/*boolean voiceMail,*/ boolean isRecording) {
		try {
			/* if (voiceMail&&isRecording) { */
			if (recorder != null) {
				recorder.stop();
				Log.e("thuutai", "Stop record");
				recorder.reset();
				recorder.release();
				recorder = null;
			/*	voiceMail = false;*/
			}
			// }
		} catch (IllegalStateException e) {
			// TODO: handle exception
			e.printStackTrace();
		} catch (NullPointerException e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}

	public static void setTimeOut(boolean timeOut) {
		VoiceMailFileController.timeOut = timeOut;
	}
	
	public static boolean getTimeout()
	{
		return timeOut;
	}

	public void Timer(ITelephony telephonyService, String incomeNumber) {
		Database db = new Database(context);
		if (db.findVoiceMailNumber(incomeNumber)) {
			Log.e("thuutai", "HAVE IN DATABASE");
			if (db.checkVoiceMailWaitTimeOut(incomeNumber)) {
				// Late
				// Do Some Thing
				Log.e("thuutai", "NO RECORD - START Voice mail WAIT"+incomeNumber);
				Timer thread1 = new Timer(telephonyService, incomeNumber,
						context);
				thread1.start();
			} else {
				// no Late
				// StartRecord
				try {
					setAllowVoiceMail(true);
					telephonyService.answerRingingCall();
					Log.e("thuutai", "ringing1");
				} catch (Exception e) {
					setAllowVoiceMail(true);
					annswerPhoneHeadsethook();
					Log.e("thuutai", "ringing2");
				}
				Log.e("thuutai", "START RECORD");
				
				db.deleteVoiceMailNumber(incomeNumber);
			}
		} else {
			Log.e("thuutai", "DONT HAVE IN DATABASE"+incomeNumber);
			Timer thread1 = new Timer(telephonyService, incomeNumber, context);
			thread1.start();
		}

	}

	public void send(VoiceMailModel processModel){	
		Uri uri = Uri.fromFile(new File(globalVar.voiceMailDir, processModel.getFileUri()));
		Intent it = new Intent(Intent.ACTION_SEND);   
		it.putExtra(Intent.EXTRA_SUBJECT, context.getString(R.string.voiceMailFile)+" "+  processModel.getCallNumber());   
		it.putExtra(Intent.EXTRA_TEXT, context.getString(R.string.date)+processModel.getCallDay()+"   "+context.getString(R.string.time)+processModel.getCallTime()); 
		it.putExtra(Intent.EXTRA_STREAM, uri);
		it.setType("audio/rfc822");   
		context.startActivity(Intent.createChooser(it,context.getString(R.string.share))); 
	}

	public void delete(VoiceMailModel processVoiceMail,
			VoiceMailActivity activity, VoiceMailAdapter adapter) {
		Database database = new Database(activity);
		if (database.countAllVocieMailCheck() != 0) {
			for (VoiceMailModel model : adapter.getList()) {
				if (model.getSeparator() == 0) {
					if (database.findVoiceMailCheck(model.getFileUri())) {
						database.deleteVoiceMailCheck(model.getFileUri());
						database.deleteVoiceMailNew(model.getFileUri());
						deleteItem(model);
					}

				}
			}

		} else {
			File file = new File(globalVar.voiceMailDir + processVoiceMail.getFileUri());
			file.delete();
			database.deleteVoiceMailNew(processVoiceMail.getFileUri());
		}

		activity.finish();
		activity.startActivity(new Intent(activity, VoiceMailActivity.class));

	}
	public void deleteItem(VoiceMailModel processModel){
		File file=new File(globalVar.voiceMailDir+processModel.getFileUri());
		file.delete();
	}
}
